import { AnyAction, Reducer } from 'redux';
import { EffectsCommandMap } from 'dva';
import { queryUserApplyRecord, approval } from './service';
import { TableListData } from './data.d';
import { message } from 'antd';
const R = require('ramda');

export interface StateType {
  data: TableListData;
}

export type Effect = (
  action: AnyAction,
  effects: EffectsCommandMap & { select: <T>(func: (state: StateType) => T) => T },
) => void;

export interface ModelType {
  namespace: string;
  state: StateType;
  effects: {
    fetch: Effect;
    add: Effect;
    remove: Effect;
    update: Effect;
  };
  reducers: {
    save: Reducer<StateType>;
  };
}

const Model: ModelType = {
  namespace: 'manageEnterpriseApproval',

  state: {
    data: {
      list: [],
      pagination: {},
    },
  },

  effects: {
    *fetch({ payload }, { call, put }) {
      const response = yield call(queryUserApplyRecord, payload);
      if (response.resultCode === 'ok') {
        const { page, list } = response.content;
        yield put({
          type: 'refreshState',
          payload: {
            data: {
              list,
              pagination: { current: page.page, total: page.totalRow, pageSize: page.size },
            },
          },
        });
      }
    },

    *approval({ payload }, { call }) {
      const response = yield call(approval, { ...R.omit(['onSuccess', 'onFail'])(payload) });
      if (response && response.resultCode === 'ok') {
        message.info('配置成功');
        if (payload.onSuccess) payload.onSuccess();
      } else {
        message.error('配置失败');
        if (payload.onFail) payload.onFail();
      }
    },
  },

  reducers: {
    /**
     * 刷新state
     *
     * @param state
     */
    refreshState(state, { payload }) {
      return { ...state, ...payload };
    },
  },
};

export default Model;
